<template>
    <div class="white-box">
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">租户账号：</span>
                <el-input placeholder="输入租户账号" v-model.trim="user_acc" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">租户ID：</span>
                <el-input placeholder="输入租户ID" v-model.trim="tenant_id" clearable> </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">版本类型：</span>
                <el-select v-model="edition_value" clearable placeholder="请选择版本类型">
                    <el-option v-for="item in editionArrs" :key="item.version_id" :label="item.title"
                        :value="item.version_id" />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
            </div>
        </div>

        <div class="table-mb">
            <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加</el-button>
        </div>

        <el-table class="table-mb" :data="arr_data" :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)" v-loading="loading">
            <el-table-column prop="enterprise_id" label="租户ID" width="100" fixed="left"></el-table-column>
            <el-table-column prop="title" label="企业名称" min-width="220" fixed="left"></el-table-column>
            <el-table-column prop="contact" label="联系人" width="100"></el-table-column>
            <el-table-column prop="mobile" label="电话(账号)" width="120"></el-table-column>
            <el-table-column prop="title" label="版本名称" width="120"></el-table-column>
            <el-table-column prop="version" label="版本号"></el-table-column>
            <el-table-column prop="domain" label="域名" width="220"></el-table-column>
            <el-table-column prop="created_at_label" label="创建时间" width="160"></el-table-column>
            <el-table-column prop="updated_at_label" label="更新时间" width="160"></el-table-column>
            <el-table-column label="操作" width="200" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button class="theme-btn" link type="primary" @click="clickRenewal(row)"> 续期 </el-button>
                    <el-button class="theme-btn" link type="primary" @click="clickEdition(row)"> 升降配 </el-button>
                    <el-button class="theme-btn" link type="primary" @click="handleEdit(row)"> 编辑 </el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消"
                        @confirm="clickDel(row)">
                        <template #reference>
                            <el-button class="theme-btn" link type="primary">删除</el-button>
                        </template>
                    </el-popconfirm>
                    <el-popconfirm title="是否确定停用？" confirm-button-text="确定" cancel-button-text="取消"
                        @confirm="clickDel(row)">
                        <template #reference>
                            <el-button class="theme-btn" link type="primary">停用</el-button>
                        </template>
                    </el-popconfirm>
                    <el-button class="theme-btn" link type="primary" @click="handleRecharge(row)"> 短信充值 </el-button>
                    <el-button class="theme-btn" link type="primary" @click="handleRecord(row)"> 短信充值记录 </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="pageSizeNum"
            :total="totalNums" layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>

        <!-- 添加/修改 -->
        <el-dialog v-model="dialogUpdate" :title="tenant_type == 1 ? '添加租户' : '编辑租户'" width="560px"
            :close-on-click-modal="false" :append-to-body="true" :destroy-on-close="true" @close="closeTenant">
            <div>
                <el-form ref="ruleTenantRef" :model="ruleTenantForm" :rules="ruleCheckTenant" label-width="120px">
                    <el-form-item label="企业名称" prop="company_name">
                        <el-input v-model="ruleTenantForm.company_name" clearable placeholder="请输入企业名称" />
                    </el-form-item>
                    <el-form-item label="联系人" prop="company_user">
                        <el-input v-model="ruleTenantForm.company_user" clearable placeholder="请输入联系人" />
                    </el-form-item>
                    <el-form-item label="电话" prop="tel">
                        <el-tooltip content="电话作为登录账号" placement="top-start">
                            <el-input v-model="ruleTenantForm.tel" oninput="value=value.replace(/[^\d.-]/g,'')"
                                maxlength="11" clearable placeholder="请输入电话" />
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="密码" prop="pass" required>
                        <el-tooltip :content="tenant_type == 2 ? '密码为空则表示不修改密码' : '请输入密码'" placement="top-start">
                            <el-input v-model="ruleTenantForm.pass" type="password" clearable placeholder="请输入密码" />
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="版本" prop="edition_id">
                        <el-select v-model="ruleTenantForm.edition_id" clearable placeholder="请选择版本类型"
                            :disabled="tenant_type == 2">
                            <el-option v-for="item in editionArrs" :key="item.version_id" :label="item.title"
                                :value="item.version_id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="域名前缀" prop="tenant_id">
                        <el-input v-model="ruleTenantForm.tenant_id" :disabled="tenant_type == 2" clearable
                            placeholder="请输入域名前缀" />
                    </el-form-item>
                    <el-form-item>
                        <div class="submit-foot">
                            <el-button type="primary" :loading="form_loading" @click="submitTenantForm(ruleTenantRef)">
                                {{ tenant_type == 1 ? "确认添加" : "立即保存" }}
                            </el-button>
                            <el-button @click="resetTenantForm(ruleTenantRef)">重置</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>

        <!-- 续期 -->
        <el-dialog v-model="dialogRenewal" title="租户续期" width="600px" :append-to-body="true" :destroy-on-close="true"
            :close-on-click-modal="false">
            <div class="custom-dialog">
                <div class="tag-item">
                    <div class="tag-item__label">到期时间</div>
                    <div class="tag-item__right">
                        <p>{{ expire_time }}</p>
                    </div>
                </div>
                <div class="tag-item">
                    <div class="tag-item__label">租户续期</div>
                    <div class="tag-item__right">
                        <el-date-picker v-model="renewal_times" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                            placeholder="请选择续期时间" />
                    </div>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" :loading="form_loading" @click="confirmRenewal">确认续期</el-button>
                    <el-button @click="dialogRenewal = false">取消</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 升降配 -->
        <el-dialog v-model="dialogRdition" title="升降配" width="600px" :append-to-body="true" :destroy-on-close="true"
            :close-on-click-modal="false">
            <div class="custom-dialog">
                <div class="tag-item">
                    <div class="tag-item__label">当前版本</div>
                    <div class="tag-item__right">
                        <p>{{ now_edition }}</p>
                    </div>
                </div>
                <div class="tag-item">
                    <div class="tag-item__label">选择版本</div>
                    <div class="tag-item__right">
                        <el-select v-model="now_edition_value" clearable placeholder="请选择版本类型">
                            <el-option v-for="item in editionArrs" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" :loading="form_loading" @click="confirmEdition">确认选择</el-button>
                    <el-button @click="dialogRdition = false">取消</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 短信充值 -->
        <el-dialog v-model="dialogRecharge" title="短信充值" width="560px" :append-to-body="true" :destroy-on-close="true"
            :close-on-click-modal="false" @close="closeRecharge">
            <el-form ref="ruleRechargeRef" :model="ruleRechargeForm" :rules="ruleCheckRecharge" label-width="120px">
                <el-form-item label="租户ID">
                    <p>{{ ruleRechargeForm.id }}</p>
                </el-form-item>
                <el-form-item label="租户名称">
                    <p>{{ ruleRechargeForm.title }}</p>
                </el-form-item>
                <el-form-item label="充值数量" prop="nums">
                    <el-input v-model="ruleRechargeForm.nums" clearable oninput="value=value.replace(/[^\d]/g,'')"
                        placeholder="请输入充值数量(条)" />
                </el-form-item>
                <el-form-item label="充值金额" prop="price">
                    <el-input v-model="ruleRechargeForm.price" clearable oninput="value=value.replace(/[^\d.]/g,'')"
                        placeholder="请输入充值金额" />
                </el-form-item>
                <el-form-item label="充值备注" prop="reason">
                    <el-input v-model.trim="ruleRechargeForm.reason" type="textarea" clearable :rows="4"
                        placeholder="请输入充值备注" style="width: 320px" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 30px">
                        <el-button type="primary" :loading="form_loading" @click="submitRechargeForm(ruleRechargeRef)"> 确认充值
                        </el-button>
                        <el-button @click="resetRechargeForm(ruleRechargeRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 短信记录 -->
        <el-dialog v-model="dialogRecord" title="短信充值记录" width="1000px" :append-to-body="true" :destroy-on-close="true"
            :close-on-click-modal="false">
            <el-table class="table-mb" v-loading="recordLoading" :data="recordArrs"
                :header-cell-style="{ background: '#F5F7FA' }" element-loading-background="rgba(255, 255, 255, 0.6)">
                <el-table-column prop="enterprise_id" label="租户ID" width="90"> </el-table-column>
                <el-table-column label="充值前短信数" width="130">
                    <template #default="{ row }">
                        <span>{{ row.old_val || 0 }}条</span>
                    </template>
                </el-table-column>
                <el-table-column label="充值条数" width="120">
                    <template #default="{ row }">
                        <span>{{ row.number || 0 }}条</span>
                    </template>
                </el-table-column>
                <el-table-column label="充值后短信数" width="130">
                    <template #default="{ row }">
                        <span>{{ row.val || 0 }}条</span>
                    </template>
                </el-table-column>
                <el-table-column label="充值金额" width="120">
                    <template #default="{ row }">
                        <span>{{ row.amount || 0 }}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="充值备注" min-width="160">
                    <template #default="{ row }">
                        <el-popover placement="top" :width="540" trigger="hover" :content="row.remark">
                            <template #reference>
                                <div class="line-two">{{ row.remark }}</div>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="created_at_label" label="充值时间" width="160"></el-table-column>
            </el-table>
            <el-pagination background v-model:current-page="recordPage" :page-size="10" :total="recordTotal"
                layout="total, prev, pager, next, jumper">
            </el-pagination>
        </el-dialog>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, watch, onBeforeUnmount } from "vue"
import OneLoad from "@mixins/one-load"
import { CirclePlus, Search } from "@element-plus/icons-vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
    getEdition()
})

//清除
onBeforeUnmount(() => {
   
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, search_btn, totalNums, pubParams, pubRefreshParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pageSize.value = val
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    page.value = val
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    getdata("enterprise/index", params)
}

const tenant_ids = ref("") // 租户ID
const form_loading = ref(false) // 公共表单按钮状态

/**
 * 搜索
 * @param {String} user_acc 租户名称
 * @param {String} tenant_id 租户ID
 * @param {String} edition_value 版本类型
 * @param {Function} handleSearch 搜索按钮
 */
const user_acc = ref("")
const tenant_id = ref("")
const edition_value = ref("")
const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

/**
 * 版本类型
 * @param {Array} editionArrs 版本数组
 * @param {Function} getEdition 获取版本
 */
const editionArrs = ref([])
function getEdition() {
    proxy.$axios
        .get("version/index")
        .then((res) => {
            if (res.data.code == 0) {
                editionArrs.value = res.data.data
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => { })
}

/**
 * 添加/编辑租户弹窗
 * @param {Boolean} dialogUpdate 弹窗状态
 * @param {Number} tenant_type 1是添加，2是编辑
 * @param {Array} ruleTenantRef 表单规则
 * @param {Object} ruleTenantForm  表单字段
 * @param {Object} ruleCheckTenant  表单提示
 * @param {Function} submitTenantForm 保存
 * @param {Function} closeTenant 关闭
 */
const dialogUpdate = ref(false)
const tenant_type = ref(1)
const handleAdd = () => {
    tenant_type.value = 1
    dialogUpdate.value = true
}
const handleEdit = (row) => {
    dialogUpdate.value = true
    setTimeout(() => {
        tenant_type.value = 2
        tenant_ids.value = row.enterprise_id
        ruleTenantForm.edition_id = row.version_id
        ruleTenantForm.company_name = row.title
        ruleTenantForm.company_user = row.contact
        ruleTenantForm.tel = row.mobile
        ruleTenantForm.tenant_id = row.tenant_id
    }, 50)
}
const ruleTenantRef = ref(null)
const ruleTenantForm = reactive({
    company_name: "",
    company_user: "",
    tel: "",
    tenant_id: "",
    pass: "",
    edition_id: "",
})
const ruleCheckTenant = reactive({
    company_name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
    company_user: [{ required: true, message: "请输入联系人", trigger: "blur" }],
    tel: [{ validator: proxy.$util.validPhone, trigger: "blur" }],
    tenant_id: [{ required: true, message: "请输入域名前缀", trigger: "blur" }],
    edition_id: [{ required: true, message: "请选择版本", trigger: "change" }],
})
const submitTenantForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (tenant_type.value == 1 && ruleTenantForm.pass == "") {
                proxy.$message({message:"请输入密码",type:"warning"})
                return
            }
            form_loading.value = true
            let data = {
                title: ruleTenantForm.company_name, // 企业名称
                contact: ruleTenantForm.company_user,
                mobile: ruleTenantForm.tel,
                password: ruleTenantForm.pass,
                tenant_id: ruleTenantForm.tenant_id, // 域名前缀
                version_id: ruleTenantForm.edition_id, // 版本ID
            }
            if (tenant_type.value == 2) {
            }
            let url = tenant_type.value == 1 ? "enterprise/add" : ""
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogUpdate.value = false
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetTenantForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeTenant = () => {
    dialogUpdate.value = false
    resetTenantForm(ruleTenantRef.value)
}

/**
 * 续期
 * @param {Boolean} dialogRenewal 弹窗状态
 * @param {String} expire_time 到期时间
 * @param {String} renewal_times 续期时间
 * @param {Function} clickRenewal 点击续期
 * @param {Function} confirmRenewal 确认续期
 */
const dialogRenewal = ref(false)
const expire_time = ref("")
const renewal_times = ref("")
const clickRenewal = (row) => {
    dialogRenewal.value = true
    setTimeout(() => {
        tenant_ids.value = row.id
        expire_time.value = row.create_time
    }, 50)
}
const confirmRenewal = () => {
    console.log("renewal_times", renewal_times.value)
    return
    form_loading.value = true
    proxy.$axios
        .post("", {})
        .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            form_loading.value = false
        })
}

/**
 * 升降配
 * @param {Boolean} dialogRdition 弹窗状态
 * @param {String} expire_time 当前版本
 * @param {String} now_edition_value 当前选择的版本
 * @param {Function} clickRenewal 点击续期
 * @param {Function} confirmEdition 确认续期
 */
const dialogRdition = ref(false)
const now_edition = ref("")
const now_edition_value = ref("")
const clickEdition = (row) => {
    dialogRdition.value = true
    edition_value.value = ""
    setTimeout(() => {
        now_edition.value = row.banben
    }, 50)
}
const confirmEdition = () => {
    return
    form_loading.value = true
    proxy.$axios
        .post("", {})
        .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            form_loading.value = false
        })
}

/**
 * 短信充值
 * @param {Boolean} dialogRecharge 弹窗状态
 * @param {Number} tenant_type 1是添加，2是编辑
 * @param {Array} ruleRechargeRef 表单规则
 * @param {Object} ruleRechargeForm  表单字段
 * @param {Object} ruleCheckRecharge  表单提示
 * @param {Function} submitRechargeForm 保存
 * @param {Function} closeRecharge 关闭
 */
const dialogRecharge = ref(false)
const ruleRechargeRef = ref(null)
const ruleRechargeForm = reactive({
    id: "",
    title: "",
    nums: "",
    price: "",
    reason: "",
})
const ruleCheckRecharge = reactive({
    nums: [{ required: true, message: "请输入充值数量", trigger: "blur" }],
    price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    reason: [{ required: true, message: "请输入充值备注", trigger: "blur" }],
})
const handleRecharge = (row) => {
    ruleRechargeForm.id = row.enterprise_id
    ruleRechargeForm.title = row.title
    dialogRecharge.value = true
}
const submitRechargeForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                enterprise_id: ruleRechargeForm.id,
                number: ruleRechargeForm.nums,
                amount: ruleRechargeForm.price,
                remark: ruleRechargeForm.reason,
            }
            proxy.$axios
                .post("enterprise/recharge", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogRecharge.value = false
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetRechargeForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeRecharge = () => {
    dialogRecharge.value = false
    resetRechargeForm(ruleRechargeRef.value)
}

/**
 * 短信充值记录
 * @param {Boolean} dialogRecord 弹窗状态
 * @param {Boolean} recordLoading 记录加载状态
 * @param {Number} recordPage 记录页码
 * @param {Number} recordTotal 记录总数
 * @param {Array} recordArrs 记录数组
 */
const dialogRecord = ref(false)
const recordArrs = ref([])
const recordPage = ref(1)
const recordTotal = ref(0)
const recordLoading = ref(false)
const handleRecord = (row) => {
    getRecord(row.enterprise_id)
    dialogRecord.value = true
}
function getRecord(id) {
    recordLoading.value = true
    proxy.$axios
        .get("enterprise/rechargeLog", {
            params: {
                enterprise_id: id,
                page: recordPage.value,
                limit: 10,
            },
        })
        .then((res) => {
            recordLoading.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                recordTotal.value = res.data.count
                recordArrs.value = res.data.current_page > 1 ? recordArrs.value.concat(result) : result
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            recordLoading.value = false
        })
}
</script>

<style lang="less" scoped>
.custom-dialog {
    margin-top: @margin-mdl;

    .tag-item {
        display: flex;
        align-items: center;
        margin-bottom: @margin-lg;

        .tag-item__label {
            flex: none;
            text-align: right;
            width: 120px;
            padding-right: @padding-md;
            font-size: @font-size-md;
            color: @gray-8;
        }

        .tag-item__right {
            flex: none;
            width: 300px;
        }
    }
}
</style>
